#include "CPhysMemUtils.h"
#include <tchar.h>

#define _PHYSICAL_MEMORY_SUPPORT
#include "WinRing0/include/OlsApiInit.h"

#pragma comment(lib, "WinRing0/lib/x64/WinRing0x64.lib")

#pragma intrinsic(memcpy)

HMODULE CPhysMemUtils::m_hModule = nullptr;

bool CPhysMemUtils::Initialize()
{
    if (nullptr != m_hModule)
    {
        return true;
    }

    return InitOpenLibSys(&m_hModule);
}

bool CPhysMemUtils::Uninitialize()
{
    if (nullptr == m_hModule)
    {
        return true;
    }

    return DeinitOpenLibSys(&m_hModule);
}

bool CPhysMemUtils::ReadPhysMem(DWORD_PTR pbPhysAddr, PBYTE buffer, DWORD size)
{
    if (nullptr == ReadPhysicalMemory)
    {
        return false;
    }

    return ReadPhysicalMemory(pbPhysAddr, buffer, size, 1);
}

bool CPhysMemUtils::WritePhysMem(DWORD_PTR pbPhysAddr, PBYTE buffer, DWORD size)
{
    if (nullptr == ReadPhysicalMemory)
    {
        return false;
    }

    return WritePhysicalMemory(pbPhysAddr, buffer, size, 1);
}

bool CPhysMemUtils::ReadByte(DWORD_PTR pbPhysAddr, uint8_t* pVal)
{
    return ReadPhysMem(pbPhysAddr, pVal, sizeof(uint8_t));
}

bool CPhysMemUtils::WriteByte(DWORD_PTR pbPhysAddr, uint8_t nVal)
{
    return WritePhysMem(pbPhysAddr, &nVal, sizeof(uint8_t));
}

bool CPhysMemUtils::GetPortValue(uint8_t port, uint8_t* pVal)
{
    if (!ReadIoPortByteEx(port, pVal))
    {
        return false;
    }

    return true;
}

bool CPhysMemUtils::SetPortValue(uint8_t port, uint8_t nVal)
{
    if (!WriteIoPortByteEx(port, nVal))
    {
        return false;
    }

    return true;
}